package com.io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class NioServer {

    static List<SocketChannel> socketChannelList=new ArrayList<>();

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocket=ServerSocketChannel.open();
        serverSocket.socket().bind(new InetSocketAddress(9000));
        serverSocket.configureBlocking(false);
        System.out.println("服务启动成功");
        while (true){
            SocketChannel socketChannel = serverSocket.accept();
            if (socketChannel!=null){
                System.out.println("连接成功");
                socketChannel.configureBlocking(false);
                socketChannelList.add(socketChannel);
            }
            Iterator<SocketChannel> iterable=socketChannelList.iterator();
            while (iterable.hasNext()){
                SocketChannel sc = iterable.next();
                ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                int len = sc.read(byteBuffer);
                if (len>0){
                    System.out.println("接收到的消息为："+new String(byteBuffer.array()));
                }else if(len==-1){
                    iterable.remove();
                    System.out.println("客户端断开连接");
                }
            }
        }
    }
}
